<template>
  <view class="page-article">
    <!-- <view class="article-main">
      <view class="article-title">{{ detail.name }}</view>
      <view class="article-desc">
        <text class="text-item">类型：{{ detail.typeName }}</text>
        <text>发布时间：{{ detail.moditime }}</text>
      </view>
      <view class="article-content">
        <text class="preline">{{ detail.content || '（无）' }}</text>
      </view>
    </view>
    <view v-if="fileList.length" class="article-download">
      <view class="block-title">文件</view>
      <view v-for="(t,i) in fileList" :key="i" class="download-item" @click="fileHandler(t)">
        <view class="download-title">{{ t.fileNote }}</view>
        <text class="status">
          查看
        </text> -->
        <!-- <text v-if="isFileSave[t.fileId]" class="status saved">
          已保存
        </text>
        <text v-else class="status">
          保存
        </text>
      </view>
    </view>
    <view v-if="linkList.length" class="article-link">
      <view class="block-title">链接</view>
      <view v-for="(t,i) in linkList" :key="i" class="link-item">
        <view class="link-name">{{ t.linkName }}</view>
        <view class="link-url"><text class="link" @click="linkView(t)">{{ t.linkUrl }}</text></view>
        <video :src='t.linkUrl'></video>
      </view>
    </view> -->
    <video autoplay loop :src='link' id='myVideo'></video>
  </view>
</template>

<script>
import { getPolicyDetail, getTrainingDetail } from "@/api";
import { downloadFile } from "@/request/request";

export default {
  data() {
    return {
      detail: {},
      fileList: [],
      linkList: [],
      isFileSave: {},
      rootPath: wx.env.USER_DATA_PATH,
      link: ''
    }
  },
  onLoad(options) {
    this.link = options.link;
    this.videoContext = wx.createVideoContext('myVideo', this);// 	创建 video 上下文 VideoContext 对象。
		this.videoContext.requestFullScreen({	// 设置全屏时视频的方向，不指定则根据宽高比自动判断。
			direction: 90						// 屏幕逆时针90度
		});
    // const { id } = options;
    // if (id) {
    //   this.getDetail(id)
    // }
  },
  methods: {
    getDetail(id) {
      id = id || this.detail.id;
      uni.showLoading();
      getTrainingDetail(id).then(res => {
        if (res) {
          this.detail = res;
          this.fileList = res.fileList || [];
          let linkList = res.linkList || [];
          this.linkList = linkList.filter(rs=>{
            let suffix = rs.linkUrl.substr(rs.linkUrl.length-4)
            return suffix == '.mp4' || suffix == '.MP4'
          })
          // 检验是否已下载
          // const _this = this;
          // this.fileList.forEach(t => {
          //   let filePath = `${this.rootPath}/${t.fileName}`;
          //   wx.getFileInfo({
          //     filePath,
          //     success() {
          //       _this.$set(_this.isFileSave, t.fileId, t.filePath);
          //     }
          //   })
          // })
        }
        uni.hideLoading();
      })
    },
    fileHandler(row) {
      let filePath = `${this.rootPath}/${row.fileName}`;
      const _this = this;
      wx.getFileInfo({
        filePath,
        success() {
          _this.previewFile(filePath)
        },
        fail() {
          _this.downloadFile(row);
        }
      })
    },
    // 二进制文件下载
    downloadFile(row) {
      let filePath = `${this.rootPath}/${row.fileName}`;
      console.log(filePath)
      const _this = this;
      uni.showLoading();
      downloadFile({ url: '/files/book-download?fileId=' + row.fileId }).then(data => {
        const fs = wx.getFileSystemManager(); //获取全局唯一的文件管理器
        fs.writeFile({ // 写文件
          filePath,
          data: data,
          encoding: "binary", //二进制流文件必须是 binary
          success(res){
            console.log('write success')
            this.previewFile(filePath);
          },
          fail(err) {
            uni.showToast({
              title: '文件执行异常',
              icon: 'none'
            })
          },
          complete() {
            uni.hideLoading();
          }
        });
      })
    },
    // 文件下载预览
    saveFile(row){
      let token = uni.getStorageSync('token');
      let filePath = `${this.rootPath}/${row.fileName}`;
      console.log(filePath)
      const _this = this;
      wx.getFileInfo({
        filePath,
        success() {
          _this.$set(_this.isFileSave, row.fileId, row.filePath);
        },
        fail() {
          wx.downloadFile({
            url: process.env.VUE_APP_BASE_URL + row.filePath,
            filePath,
            header: {
              'x-token': token || '1234567890'
            },
            success: res => {
              // let filePath = res.tempFilePath;
              _this.$set(_this.isFileSave, row.fileId, row.filePath);
            },
            fail() {
              uni.showToast({
                title: '文件下载失败！',
                icon: 'none'
              })
            }
          })
        }
      })
    },
    // 文件预览
    previewFile(filePath) {
      let imgType = ['.png', '.jpg', '.jpeg'], isImage = false;
      imgType.forEach(t => {
        if (filePath.indexOf(t) != -1) isImage = true;
      })
      if (isImage) {
        // 图片预览
        wx.previewImage({
          urls: [filePath],
          fail() {
            uni.showToast({
              title: '打开图片失败',
              icon: 'none'
            })
          }
        })
      } else {
        // 文件预览
        wx.openDocument({
          filePath,
          fail() {
            uni.showToast({
              title: '打开文档失败',
              icon: 'none'
            })
          }
        })
      }
    },
    linkView(row) {
      uni.setClipboardData({
        data: row.linkUrl,
        success: function () {
          uni.showToast({
            title: '已复制链接，请用浏览器打开',
            icon: 'none'
          })
        }
      });
      // uni.navigateTo({
      //   url: `/pages/webView?url=${row.linkUrl}`,
      // })
    }
  }
}
</script>

<style lang="scss" scoped>
.page-article {
  min-height: 100vh;
  background-color: #F9F9F9;
  #myVideo{
    width:100%;
  }
  .article-main {
    background-color: #fff;
    padding: 40rpx;
  }
  .article-title {
    font-size: 36rpx;
    color: #2C9AF1;
    margin-bottom: 20rpx;
  }
  .article-desc {
    font-size: 30rpx;
    color: #999;
    .text-item {
      margin-right: 20rpx;
    }
  }
  .block-title {
    margin-bottom: 20rpx;
    font-size: 30rpx;
    color: #666;
  }
  .article-content {
    padding: 40rpx 0;
    font-size: 30rpx;
    color: #333;
    .preline {
      white-space: pre-line;
    }
  }
  .article-download {
    margin-top: 40rpx;
    padding: 0 40rpx;
    .download-item {
      background-color: #fff;
      border-radius: 16rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 36rpx;
      padding: 40rpx 30rpx;
      margin-bottom: 20rpx;
      box-shadow: 0 8rpx 8rpx #E5E5E5;
      .download-title {
        flex: 1;
        color: #000;
      }
    }
    .status {
      margin-left: 40rpx;
      color: #2C9AF1;
      &.saved {
        color: #09BB07;
      }
    }
  }
  .article-link {
    margin-top: 40rpx;
    padding: 0 40rpx;
    .link-item {
      background-color: #fff;
      border-radius: 10rpx;
      font-size: 36rpx;
      padding: 40rpx 30rpx;
      margin-bottom: 20rpx;
      box-shadow: 0 8rpx 8rpx #E5E5E5;
      color: #000;
    }
    .link-name {
      margin-bottom: 20rpx;
    }
    .link-url {
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .link {
      color: #2C9AF1;
      word-break:break-all;
    }
  }
}
</style>